const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const axios = require('axios');

// 百度翻译配置
const APP_ID = '20250624002389071';
const SECRET_KEY = 'N6OC4WzlPnNPihNOu52T';

// 生成签名
function makeSign(query, salt) {
  const str = APP_ID + query + salt + SECRET_KEY;
  return crypto.createHash('md5').update(str).digest('hex');
}

// 翻译函数
async function translateBaidu(query, from = 'zh', to = 'en') {
  const salt = Date.now();
  const sign = makeSign(query, salt);

  const url = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
  const params = {
    q: query,
    from,
    to,
    appid: APP_ID,
    salt,
    sign,
  };

  try {
    const res = await axios.get(url, { params });
    if (res.data && res.data.trans_result && res.data.trans_result.length > 0) {
      return res.data.trans_result.map(item => item.dst).join('\n');
    } else {
      throw new Error('Baidu Translation API returned an exception: ' + JSON.stringify(res.data));
    }
  } catch (err) {
    throw err;
  }
}

// 测试翻译
(async () => {
  try {
    const text = 'Test the translation';
    const result = await translateBaidu(text, 'zh', 'en');
    console.log('Translation result:', result);
  } catch (err) {
    console.error('Translation error:', err);
  }
})();
